package com.xbang.attendance.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;

import com.xbang.attendance.entity.product.Product;
import com.xbang.attendance.entity.stock.Inventory;
import com.xbang.attendance.entity.system.Warehouse;
import com.xbang.attendance.security.support.SecurityUserHolder;
import com.xbang.attendance.service.InventoryService;
import com.xbang.attendance.service.ProductService;
import com.xbang.attendance.service.WarehouseService;
import com.xbang.core.utils.ReflectionUtils;

/**
 * @author huawei
 * @email alonelaval@gmail.com
 */
// @Service("stockAnalyzeService")
public class StockAnalyzeServiceImpl extends AbstractAnalyzeService {

	// @Autowired
	private WarehouseService warehouseService;
	// @Autowired
	private ProductService productService;
	// @Autowired
	private InventoryService inventoryService;

	private Map<String, String> fieldMapping = new HashMap<String, String>();

	@Override
	public void analyse(File file) throws Exception {
		POIFSFileSystem fs = null;
		HSSFWorkbook wb = null;
		fs = new POIFSFileSystem(new FileInputStream(file));
		wb = new HSSFWorkbook(fs);
		HSSFSheet sheet = wb.getSheetAt(0);
		setupExcelFieldMappings(sheet);

		int warehouseNumberColumnIndex = excelFieldMapping.get("仓储编号");
		int productNumberColumnIndex = excelFieldMapping.get("产品编号");
		int amountColumnIndex = excelFieldMapping.get("产品数量");
		int poNumberColumnIndex = excelFieldMapping.get("Sales Order NO");
		int poDateColumnIndex = excelFieldMapping.get("SO Date");
		for (Row row : sheet) {
			// /头
			if (row.getRowNum() == 0) {
				continue;
			}
			// 空行
			if (getCellValue(row.getCell(warehouseNumberColumnIndex)) == null
					|| getCellValue(row.getCell(warehouseNumberColumnIndex)).toString().trim().isEmpty()) {
				continue;
			}

			analyseSignInventoryByRow(row, warehouseNumberColumnIndex, productNumberColumnIndex, amountColumnIndex, poNumberColumnIndex, poDateColumnIndex);

		}
	}

	/**
	 * 解析每一行的入库记录
	 * 
	 * @param row
	 *            行
	 * @param warehouseNumberColumnIndex
	 *            仓库编码Index
	 * @param productNumberColumnIndex
	 *            产品编码Index
	 * @param amountColumnIndex
	 *            入库产品数量Index
	 * @param poNumberColumnIndex
	 *            SO number Index
	 * @param poDateColumnIndex
	 *            SO Date Index
	 * @throws Exception
	 */
	private void analyseSignInventoryByRow(Row row, int warehouseNumberColumnIndex, int productNumberColumnIndex, int amountColumnIndex,
			int poNumberColumnIndex, int poDateColumnIndex) throws Exception {
		String warehouseCode = ReflectionUtils.parseString(getCellValue(row.getCell(warehouseNumberColumnIndex)));
		Warehouse warehouse = null;
		if (warehouseCode != null && !warehouseCode.isEmpty()) {
			warehouse = warehouseService.getWarehouseByCode(warehouseCode);
			if (warehouse == null) {
				// throw new Exception("存储商" + warehouseCode + "不存在!");
			}
		}
		String productCode = ReflectionUtils.parseString(getCellValue(row.getCell(productNumberColumnIndex)));
		Product product = null;
		if (productCode != null && !productCode.isEmpty()) {
			product = productService.getProductByCode(productCode);
		}
		if (product == null) {
			// throw new Exception("产品" + productCode + "不存在！");
		}

		Object tmpDateObject = getDateCellValue(row.getCell(poDateColumnIndex));

		Date soDate = tmpDateObject == null ? null : (Date)tmpDateObject;
		String poNumber = ReflectionUtils.parseString(getCellValue(row.getCell(poNumberColumnIndex)));
		BigDecimal tmpAmount = getCellValue(row.getCell(amountColumnIndex)) != null  ? new BigDecimal(getCellValue(row.getCell(amountColumnIndex)).toString())
				: new BigDecimal(0);

		// 库存
		Inventory inventory = warehouse == null || product == null ? null : inventoryService.getInventoryByParameters(warehouse, product);

		if (inventory != null) {
			// 新增
//			inventory = new Inventory();
//			inventory.initial(warehouse, product, tmpAmount);
//
//			inventoryService.save(inventory);
			inventory.setAmount(inventory.getAmount().add(tmpAmount));
			inventory.updateOperation(SecurityUserHolder.getCurrentUser().getUsername());
			inventoryService.update(inventory);
			inventoryService.updateInventoryRecordByReplenishment(warehouse, product, inventory, poNumber, soDate, tmpAmount);
			
			inventoryService.updateInventoryWarning(inventory);
		}
//		} else {
//			// 更新 update.
//		
//		}

		

		//inventoryService.updateInventoryExchangeAgreementAmount(inventory);
		//inventoryService.updateInventoryWarning(inventory);
	}

	public static void main(String[] args) {
		BigDecimal big1 = new BigDecimal(2);
		BigDecimal big2 = new BigDecimal(3);
		BigDecimal big3 = new BigDecimal(10);
		System.out.println(big1.compareTo(big2));
		System.out.println(big3.subtract(big2.subtract(big1)));
	}

	/**
	 * @param warehouseService
	 *            the warehouseService to set
	 */
	public void setWarehouseService(WarehouseService warehouseService) {
		this.warehouseService = warehouseService;
	}

	/**
	 * @param productService
	 *            the productService to set
	 */
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	/**
	 * @param inventoryService
	 *            the inventoryService to set
	 */
	public void setInventoryService(InventoryService inventoryService) {
		this.inventoryService = inventoryService;
	}

	/**
	 * @param fieldMapping
	 *            the fieldMapping to set
	 */
	public void setFieldMapping(Map<String, String> fieldMapping) {
		this.fieldMapping = fieldMapping;
	}

}
